import React, { useState } from 'react';
import * as Diff from 'diff';
import { html } from 'diff2html';
import { Button } from 'antd';
import 'diff2html/bundles/css/diff2html.min.css';
import styles from './style.module.css';

const JsonDiffTool: React.FC = () => {
  const [json1, setJson1] = useState<string>('');
  const [json2, setJson2] = useState<string>('');
  const [diffHtml, setDiffHtml] = useState<string>('');

  const generateDiff = () => {
    try {
      const formattedJson1 = JSON.stringify(JSON.parse(json1), null, 2);
      const formattedJson2 = JSON.stringify(JSON.parse(json2), null, 2);

      const diff = Diff.createPatch('json.json', formattedJson1, formattedJson2, '', '', { context: 1000 });
      
      if (diff) {
        const diffJson = html(diff, {
          drawFileList: false,
          matching: 'lines',
          outputFormat: 'side-by-side',
        });
        setDiffHtml(diffJson);
      }
    } catch (error) {
      setDiffHtml('<p style="color: red;">无效的JSON格式</p>');
    }
  };

  return (
    <div className={styles.container}>
      <div className={styles.inputs}>
        <div className={styles.textareaContainer}>
          <textarea
            value={json1}
            onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => setJson1(e.target.value)}
            placeholder="输入第一个JSON"
          />
        </div>
        <div className={styles.textareaContainer}>
          <textarea
            value={json2}
            onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => setJson2(e.target.value)}
            placeholder="输入第二个JSON"
          />
        </div>
      </div>
      <div className={styles.buttonContainer}>
        <Button type="primary" onClick={generateDiff}>
          对比
        </Button>
      </div>
      <div className={styles.diffResult}>
        <div
          dangerouslySetInnerHTML={{ __html: diffHtml }}
        />
      </div>
    </div>
  );
};

export default JsonDiffTool; 